clear; clc; close all;
tic
suffixes = {'1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'; '10'};
dataPrefix = 'CDS';
dataType = 'LD';
dir = 'C:\Users\Mittal\Documents\Work\Code\survival-analysis\perl\LR_CDS_NTDB_TrainCDS+NTDB_TestCDS_Imputed\35-65\';

for isuffix = 1:length(suffixes),
    suffix = suffixes{isuffix};
    clearvars -except suffix suffixes dataPrefix dataType dir
    data_MM = load([dir 'CDS_NTDB_Train' dataPrefix '_TestCDS_Imputation_Train_' dataType '_CDS_1_NTDB_1_35-65_' suffix '_mice_imputed_0_MM.txt']);
    data = spconvert(data_MM);
    Y = data(:,1);
    X = data(:,2:end);
    X = X - repmat(mean(X),size(X,1),1);
    for iX = 1:size(X,2),
        normi = norm(X(:,iX));
        if(normi ~= 0)
        	X(:,iX) = X(:,iX)/normi;
        end
    end
    
    [~,S,V] = svds(X);
    lambda2 = (V*S*V').^2;

    betaTemp = ReadModelFile([dir 'modelfile_Train' dataPrefix '_TestCDS_Imputation_' dataType '_CDS_1_NTDB_1_35-65_' suffix  '_mice_imputed_0.txt']);
    intercept = betaTemp(1,2);
    betaTemp = sortrows(betaTemp(2:end,:));
    beta = [[1:size(V,1)]' zeros(size(V,1),1)];
    beta(betaTemp(:,1),2) = betaTemp(:,2);
    beta = beta(:,2);
    beta(1) = [];
    if(length(beta) < size(V,1))
        beta(end+1) = 0;
    end
    betaX = intercept + data(:,2:end)*beta;
    LPredY = 1./(1 + exp(-betaX));
    lYhat = log(LPredY./(1-LPredY));
    stdlYhat = std(lYhat);
    Rsq = (sum((LPredY-mean(Y)).^2))/(sum((Y-mean(Y)).^2));
    betaStand = beta*(sqrt(Rsq)/stdlYhat);
    epsilon = lambda2*(betaStand.^2);
    PropWeights = epsilon/sum(epsilon);
    
    RawRelWeight = epsilon;
    RescaledRelWeight = PropWeights;
    keys = textread([dir 'CDS_NTDB_TrainCDS+NTDB_TestCDS_Imputation_Keys.txt'],'%s','whitespace','\n');
    fid = fopen([dir 'RawRelWeights_' dataPrefix '_' dataType '_' suffix '.txt'],'w');
    for i = 1:length(RawRelWeight),
        fprintf(fid,'%s#$#$#%d\n',keys{i}, RawRelWeight(i));
    end
    fclose(fid);
       
    fid = fopen([dir 'RescaledRelWeights_' dataPrefix '_' dataType '_' suffix '.txt'],'w');
    for i = 1:length(RescaledRelWeight),
        fprintf(fid,'%s#$#$#%d\n',keys{i}, RescaledRelWeight(i));
    end
    fclose(fid);
        
    fid = fopen([dir 'beta_' dataPrefix '_' dataType '_' suffix '.txt'],'w');
    for i = 1:length(beta),
        fprintf(fid,'%s#$#$#%d\n',keys{i}, beta(i));
    end
    fclose(fid);
end
toc